import React, { useEffect, useRef, useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { ImageBackground, StatusBar, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { CommonStyle } from '../../common/commonStyle.ts';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Toast from 'react-native-toast-message';
import background from '../../assets/images/bacgroun_login.png';
import { useBoolean } from 'ahooks';
import Spinner from 'react-native-loading-spinner-overlay';
import { AppDispatch, RootState } from '../../redux/store.ts';
import { useDispatch, useSelector } from 'react-redux';
import StorageUtil from '../../utils/Storage.ts';
import to from '../../utils/to.ts';
import { fetchInitialUserInfo, removeShoppingCart } from '../../redux/reducers/app.ts';
import { WX_APPID } from '../../common/config.ts';
import UserRequest from '../../request/userRequest.ts';

interface ICheckSmsCaptchaScreenProps {
  navigation: NavigationProp<any, 'checkSmsCaptchaScreen'>;
  route: RouteProp<{ checkSmsCaptchaScreen: any }, 'checkSmsCaptchaScreen'>;
}
const CheckSmsCaptchaScreen: React.FC<ICheckSmsCaptchaScreenProps> = ({ navigation, route }) => {
  const { params } = route;
  const insets = useSafeAreaInsets();
  const [check, setCheck] = useState<boolean>(false);
  const input1Ref = useRef<TextInput | null>(null);
  const input2Ref = useRef<TextInput | null>(null);
  const input3Ref = useRef<TextInput | null>(null);
  const input4Ref = useRef<TextInput | null>(null);
  const input5Ref = useRef<TextInput | null>(null);
  const input6Ref = useRef<TextInput | null>(null);
  const [inputValues, setInputValues] = useState<string[]>(['', '', '', '', '', '']);
  const [timeLeft, setTimeLeft] = useState<number>(60);
  const [isRunning, setIsRunning] = useState<boolean>(true);
  const [spinner, { toggle, setTrue, setFalse }] = useBoolean(false);
  const [spinnerText, setSpinnerText] = useState<string>('发送验证码...');
  const registerID = useSelector((state: RootState) => state.registerID);
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    input1Ref.current?.focus();
  }, []);

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (isRunning && timeLeft > 0) {
      timer = setInterval(() => {
        setTimeLeft((prevTime) => prevTime - 1);
      }, 1000);
    } else if (timeLeft === 0) {
      setIsRunning(false);
    }
    return () => clearInterval(timer);
  }, [isRunning, timeLeft]);

  /**
   * 重新开始
   */
  const handleResend = () => {
    setSpinnerText('发送验证码...');
    if (isRunning) {
      Toast.show({ type: 'error', text1: `请等待${timeLeft}秒后再重试` });
      return;
    }
    setTrue();
    UserRequest.FetchSMS({ mobile: params!.phone, smsType: 101 })
      .then(() => {
        setFalse();
        Toast.show({ type: 'success', visibilityTime: 1000, text1: '发送验证码成功，请注意查看短信' });
        setTimeLeft(60);
        setIsRunning(true);
      })
      .catch(() => {
        setFalse();
      });
  };

  useEffect(() => {
    setCheck(!inputValues.some((item) => item === ''));
  }, [inputValues]);

  /**
   *
   * @param text
   * @param inputIndex
   * @param nextInputRef
   */
  const handleTextChange = (text: string, inputIndex: number, nextInputRef: React.RefObject<TextInput | null>) => {
    const newInputValues = [...inputValues];
    newInputValues[inputIndex] = text.length === 1 ? text : '';
    setInputValues(newInputValues);

    if (text.length === 1 && nextInputRef.current) {
      nextInputRef.current.focus();
    }
  };

  /**
   * 登录
   */
  const onPressByLogin = async () => {
    setSpinnerText('登录中...');
    setTrue();

    const loginParams = {
      userName: params!.phone,
      code: Number(inputValues.join('')),
      appId: WX_APPID,
      loginType: 10,
      tenantId: '1510456530575347712',
      userRole: 2,
    };
    UserRequest.Login(loginParams)
      .then(async (res) => {
        setFalse();
        const [tokenErr] = await to(StorageUtil.save<string>('token', res.data.userCode));
        const [userErr] = await to(StorageUtil.save<ILoginResponse>('userInfo', res.data));
        dispatch(fetchInitialUserInfo());
        if (tokenErr || userErr) {
          Toast.show({ type: 'error', text1: '登录失败，请联系客服' });
          return;
        }
        Toast.show({ type: 'success', text1: '登录成功 🎉' });
        dispatch(removeShoppingCart());
        navigation.navigate('tab');
      })
      .catch(() => {
        setFalse();
      });
  };

  return (
    <>
      {/** 隐藏状态栏 */}
      <StatusBar translucent backgroundColor={'transparent'} barStyle="dark-content" />
      <ImageBackground style={commonStyles.root} source={background}>
        <Spinner visible={spinner} textContent={spinnerText} color={CommonStyle.mainColor} overlayColor={'rgba(0, 0, 0, 0.01)'} textStyle={CommonStyle.spinnerText} />
        <View style={[styles.root, { top: insets.top + 10 }]}>
          <View style={styles.root}>
            {/** 密码登录提示 */}
            <Text style={styles.phoneLoginTitle}>输入短信验证码</Text>
            <Text style={styles.phoneLoginSubTitle}>已经向您的手机 {params!.phone} 发送验证码</Text>

            <View style={styles.smsRoot}>
              <TextInput ref={input1Ref} style={styles.smsInput} keyboardType="numeric" maxLength={1} onChangeText={(text) => handleTextChange(text, 0, input2Ref)} />
              <TextInput ref={input2Ref} style={styles.smsInput} keyboardType="numeric" maxLength={1} onChangeText={(text) => handleTextChange(text, 1, input3Ref)} />
              <TextInput ref={input3Ref} style={styles.smsInput} keyboardType="numeric" maxLength={1} onChangeText={(text) => handleTextChange(text, 2, input4Ref)} />
              <TextInput ref={input4Ref} style={styles.smsInput} keyboardType="numeric" maxLength={1} onChangeText={(text) => handleTextChange(text, 3, input5Ref)} />
              <TextInput ref={input5Ref} style={styles.smsInput} keyboardType="numeric" maxLength={1} onChangeText={(text) => handleTextChange(text, 4, input6Ref)} />
              <TextInput ref={input6Ref} style={styles.smsInput} keyboardType="numeric" maxLength={1} onChangeText={(text) => handleTextChange(text, 5, input6Ref)} />
            </View>

            {/** 重新发送按钮 */}
            <View style={commonStyles.protocolLayout}>
              <TouchableOpacity onPress={handleResend}>
                <Text style={commonStyles.labelText}>{timeLeft ? timeLeft + 's后可' : ''}重新发送</Text>
              </TouchableOpacity>
            </View>

            {/** 下一步按钮 */}
            <TouchableOpacity style={check ? styles.loginButton : CommonStyle.unLoginButton} activeOpacity={check ? 0.7 : 1} onPress={onPressByLogin}>
              <Text style={styles.loginText}>登 录</Text>
            </TouchableOpacity>
          </View>
        </View>
      </ImageBackground>
    </>
  );
};

const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    flexDirection: 'column',
    alignItems: 'flex-start',
    paddingHorizontal: 20,
  },

  phoneLoginTitle: {
    fontSize: 24,
    color: 'black',
    fontWeight: 'bold',
    marginTop: 54,
  },

  phoneLoginSubTitle: {
    fontSize: 12,
    color: CommonStyle.deepGrey,
    marginTop: 10,
  },
  loginButton: {
    width: '100%',
    height: 40,
    backgroundColor: CommonStyle.mainColor,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
    marginTop: 22,
  },

  loginText: {
    fontSize: 13,
    color: 'white',
    fontWeight: 'bold',
  },

  smsRoot: {
    paddingTop: 20,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },

  smsInput: {
    width: 40,
    height: 40,
    borderWidth: 0.5,
    borderColor: CommonStyle.normalGrey,
    textAlign: 'center',
    fontSize: 13,
    fontWeight: 'bold',
    marginHorizontal: 5,
  },
});

const commonStyles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    backgroundColor: 'white',
    flexDirection: 'column',
    alignItems: 'center',
  },

  protocolLayout: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
    marginTop: 15,
  },

  radioButton: {
    width: 20,
    height: 20,
  },

  labelText: {
    fontSize: 11,
    color: CommonStyle.fontColor,
  },

  protocolText: {
    fontSize: 10,
    color: '#1020ff',
  },
});

export default CheckSmsCaptchaScreen;
